import BaseLayer from "../Base/BaseLayer";
import { EBundleType, EGameType, EResType } from "../Common/Enum";
import { GlobalData } from "../Common/GlobalData";
import { ETalkType, TalkModule } from "../Common/TalkModule";
import TaskModule from "../Common/TaskModule";
import { IGameData, ITalkData, ITaskData, ITimeData } from "../Interface/IMessage";
import { AdManager } from "../naodong/ads/AdManager";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../naodong/base/EnumIndex";
import { EventManager } from "../naodong/manager/EventManager";
import { ResManager1 } from "../naodong/manager/ResManager1";
import { UIManager } from "../naodong/manager/UIManager";
import { SceneGame } from "../SceneGame";
import AudioManager from "../Util/AudioManager";
import { LoadUtil } from "../Util/LoadUtil";
import StorageUtil from "../Util/StorageUtil";
import HomeUI from "./home/HomeUI";
import { LayerGame } from "./LayerGame";
import TownUI from "./town/TownUI";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameUI extends BaseLayer {
    public static instance: GameUI = null;

    @property({ type: cc.Node, tooltip: "任务按钮" })
    private btnTask: cc.Node = null;
    @property({ type: cc.Node, tooltip: "回家/出门按钮" })
    private btnHome: cc.Node = null;
    @property({ type: cc.Node, tooltip: "背包按钮" })
    private btnBag: cc.Node = null;
    @property({ type: cc.Node, tooltip: "聊天按钮" })
    private btnChat: cc.Node = null;
    @property({ type: cc.Node, tooltip: "功法按钮" })
    private btnNitpick: cc.Node = null;

    @property({ type: cc.Node, tooltip: "抖音侧边栏按钮" })
    public btnDyReward: cc.Node = null;
    @property({ type: cc.Node, tooltip: "抖音录屏按钮" })
    public btnRecord: cc.Node = null;

    @property({ type: cc.Node, tooltip: "出门" })
    private go: cc.Node = null;
    @property({ type: cc.Node, tooltip: "回家" })
    private back: cc.Node = null;

    @property({ type: cc.Sprite, tooltip: "头像" })
    private icon: cc.Sprite = null;


    @property(cc.Label)
    private labDay: cc.Label = null;
    @property(cc.Label)
    private labHour: cc.Label = null;

    private gameData: IGameData = null;
    private talkData: ITalkData = null;
    public taskData: ITaskData = null;
    private timeData: ITimeData = null;

    protected start() {
        GameUI.instance = this;

        this.gameData = StorageUtil.instance.getGameData();
        this.talkData = StorageUtil.instance.getTalkData();
        this.taskData = StorageUtil.instance.getTaskData();
        this.timeData = StorageUtil.instance.getTimeData();

        GlobalData.recordType = '开始录';

        this.initGiftBtn();
        this.recorder();

        this.updateBtn();
        this.updateUI();
        this.updateTime();
        this.showBtns();
        this.showTips();
    }

    protected onEnable() {
        EventManager.ins.on(EVENT_NAME_ENUM.HIDE_GIFT_BTN, this.hideGiftBtn, this);
        EventManager.ins.on(EVENT_NAME_ENUM.SHARE_SUCESS, this.resetRecorderIcon, this);

        const settingDatas = StorageUtil.instance.getSettingData();
        for (let i = 0; i < settingDatas.length; i++) {
            const data = settingDatas[i];
            if (data.isSelected === 1) {
                const config = GlobalData.getSettingIcon(data.id);
                LoadUtil.instance.setSpriteFrame(this.icon, EResType.BubbleIcon, config.name, 95, 95);
                break;
            }
        }
    }
    protected onDisable() {
        EventManager.ins.off(EVENT_NAME_ENUM.HIDE_GIFT_BTN, this.hideGiftBtn, this);
        EventManager.ins.off(EVENT_NAME_ENUM.SHARE_SUCESS, this.resetRecorderIcon, this);
    }

    initGiftBtn() {
        // this.giftBtn.active = true;
        AdManager.isShowGiftBtn((active: boolean) => {
            this.btnDyReward.active = active;
        });
    }

    hideGiftBtn() {
        this.btnDyReward.active = false;
    }

    resetRecorderIcon() {
        GlobalData.recordType = '开始录';
        this.recorder(true);
    }

    /** 录屏 */
    private times: number = 0;
    recorder(isInit: boolean = true) {
        if (Date.now() - this.times <= 3000) {
            console.log("3s");
            return;
        }

        this.btnRecord.children.forEach((o, i) => {
            o.active = false;
        });
        let showIndex = 0;
        switch (GlobalData.recordType) {
            case '开始录':
                {
                    if (isInit) {
                        showIndex = 0;
                        GlobalData.recordType = '开始录';
                    } else {
                        showIndex = 1;
                        GlobalData.recordType = '录屏中';
                        AdManager.startVideoScreen();

                        this.times = Date.now();
                    }
                    this.btnRecord.children[showIndex].active = true;
                }
                break;
            case '录屏中':
                {
                    if (isInit) {
                        showIndex = 1;
                        GlobalData.recordType = '录屏中';
                    } else {
                        showIndex = 2;
                        GlobalData.recordType = '待分享'; 
                        AdManager.stopVideoScreen();
                    }
                    this.btnRecord.children[showIndex].active = true;
                }
                break;
            case '待分享':
                {
                    if (isInit) {
                        showIndex = 2;
                        GlobalData.recordType = '待分享';
                    } else {
                        showIndex = 2;
                        GlobalData.recordType = '待分享';
                        AdManager.shareVideoScreen();
                    }
                    this.btnRecord.children[showIndex].active = true;
                }
                break;
        }
    }

    private updateTime() {
        cc.tween(this.node).repeatForever(
            cc.sequence(
                cc.delayTime(1),
                cc.callFunc(() => {
                    this.timeData.sceond += this.timeData.timeScale;
                    if (this.timeData.sceond >= 60) {
                        this.timeData.sceond = 0;
                        this.timeData.hour++;
                        if (this.timeData.hour >= 24) {
                            this.timeData.hour = 0;
                            this.timeData.day++;
                        }
                        if (TownUI.instance) {
                            TownUI.instance.changeDayorEvening();
                        }
                    }
                    this.updateUI();
                }),
            ),
        ).start();
    }

    private updateUI() {
        this.labDay.string = `第${this.timeData.day}天`;
        this.labHour.string = `${this.string(this.timeData.hour)}:${this.string(this.timeData.sceond)}`;
    }

    private updateBtn() {
        this.go.active = GlobalData.gameView === EGameType.Home;
        this.back.active = !this.go.active;
    }

    public check() {
        this.showBtns();
        this.showTask();
        this.showTips();
    }

    private isChatTip: boolean = false;
    private showTips() {
        const talk = TalkModule.getSayConfigById(this.talkData.id);
        if (talk && talk.type === ETalkType.Chat) {
            if (!this.isChatTip) {
                AudioManager.instance.playSound('信息提示');
                this.animation(this.btnChat);
            }
            this.isChatTip = true;
        } else {
            this.isChatTip = false;
            this.hideTips(this.btnChat);
        }

        // 展示回家/出门提示
        if (this.talkData.id === 10204 || this.talkData.id === 10305 || this.talkData.id === 10510 || this.talkData.id === 10608 || this.talkData.id === 11001) {
            this.hideTips(this.back);
            this.animation(this.go);
        } else if (this.talkData.id === 10205 || this.talkData.id === 10412 || this.talkData.id === 10903) {
            this.hideTips(this.go);
            this.animation(this.back);
        } else {
            this.hideTips(this.go);
            this.hideTips(this.back);
        }
    }

    /** 主动弹出任务层 */
    private async showTask() {
        if (this.talkData) {
            switch (this.talkData.id) {
                case 10204:        // 维修屋顶(获取铁板)
                case 10305:        // 获得启动资金(获取手镯)
                case 10510:        // 获得第一桶金(获取生肖符咒)
                case 10608:        // 为妈妈求医问药
                case 10802:        // 成为医馆学徒
                case 10903:        // 帮妈妈针灸治病
                case 11001:        // 前往矿山获取五行珠
                case 11008:        // 收购小卖店
                    {
                        if (this.taskData.isAutoShow === 0) {
                            this.taskData.isAutoShow = 1;
                            TaskModule.instance.showTask(null);
                        }
                    }
                    break;
            }
        }
    }

    public showBtns() {
        this.btnTask.active = false;
        this.btnHome.active = false;
        this.btnBag.active = false;
        this.btnChat.active = false;
        this.btnNitpick.active = false;

        this.btnTask.active = this.talkData.id >= 10005;
        if (this.talkData.id === 10005) {
            this.animation(this.btnTask);
            SceneGame.instance.showGuideUI(this.btnTask);
        }

        this.btnChat.active = this.talkData.id >= 10101;
        if (this.talkData.id === 10101) {
            this.animation(this.btnChat);
            // 虽然解锁手机，但是位置应该在房子
            SceneGame.instance.showGuideUI(this.btnHome);
        }

        this.btnBag.active = this.talkData.id >= 10204;
        this.btnHome.active = this.talkData.id >= 10204;

        this.btnNitpick.active = this.talkData.id >= 10411;
        if (this.talkData.id === 10411) {
            this.animation(this.btnNitpick);
            SceneGame.instance.showGuideUI(this.btnNitpick);
        }
    }

    private animation(node: cc.Node) {
        const tips = cc.find("tips", node);
        if (tips) {
            tips.active = true;
            tips.stopAllActions();
            cc.tween(tips).repeat(2,
                cc.sequence(
                    cc.fadeIn(0),
                    cc.fadeOut(0.1),
                    cc.delayTime(0.3),
                    cc.fadeIn(0.1),
                    cc.delayTime(0.3),
                )
            ).start();
        }
    }

    private hideTips(node: cc.Node) {
        const tips = cc.find("tips", node);
        if (tips) {
            tips.active = false;
        }
    }

    private string(value: number) {
        if (value < 10) {
            return '0' + value;
        }
        return value < 10 ? `0${value}` : value;
    }

    private async onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case 'btnTask':
                {
                    const config = TaskModule.instance.getTaskConfig();
                    if (!config) {
                        SceneGame.instance.showToast(cc.v2(0, 0), '任务已完成~');
                        return;
                    }

                    // 隐藏提示
                    this.hideTips(this.btnTask);
                    SceneGame.instance.hideGuideUI();
                    TaskModule.instance.showTask(null);
                    setTimeout(() => {
                        HomeUI.instance.showLaJiGuide();
                    }, 1200);
                }
                break;
            case 'btnSet':
                {
                    SceneGame.instance.showPopView('SettingUI');
                }
                break;
            case 'nitpick':
                {
                    if (this.talkData.id < TalkModule.OPEN_NITPICK) {
                        SceneGame.instance.showToast(cc.v2(0, 0), "暂未开启~");
                        return;
                    }

                    // 隐藏引导
                    this.hideTips(this.btnNitpick);
                    SceneGame.instance.hideGuideUI();

                    SceneGame.instance.showLoadingUI();
                    await ResManager1.ins.loadHomeAssetsBundle();
                    await ResManager1.ins.loadLevelSprBundle();
                    await ResManager1.ins.loadGameAssetsBundle();
                    await ResManager1.ins.loadRes('prefab/node/lvItem', cc.Prefab, BUNDLE_TYPE_ENUM.HOME);
                    // AudioManager.instance.stopMusic();
                    UIManager.ins.showUI("LevelUI", BUNDLE_TYPE_ENUM.HOME);
                    SceneGame.instance.hideLoadingUI();
                    console.log("打开功法页面");
                }
                break;
            case 'phone':
                {
                    if (this.talkData.id < TalkModule.OPEN_CHAT) {
                        SceneGame.instance.showToast(cc.v2(0, 0), "暂未开启~");
                        return;
                    }

                    // 隐藏引导
                    this.hideTips(this.btnChat);
                    SceneGame.instance.hideGuideUI();
                    SceneGame.instance.showPopView('ChatUI');
                }
                break;
            case 'bag':
                {
                    if (this.talkData.id < TalkModule.OPEN_MINE) {
                        SceneGame.instance.showToast(cc.v2(0, 0), "暂未开启~");
                        return;
                    }
                    SceneGame.instance.showPopView('BagUI', { type: "背包" });
                }
                break;
            case 'come':
                {
                    if (this.talkData.id < TalkModule.OPEN_MINE) {
                        SceneGame.instance.showToast(cc.v2(0, 0), "暂未开启~");
                        return;
                    }

                    // 隐藏引导
                    this.hideTips(this.btnHome);
                    SceneGame.instance.hideGuideUI();

                    SceneGame.instance.removeAllPopView();
                    // 切换页面
                    if (GlobalData.gameView === EGameType.Home) {
                        GlobalData.gameView = EGameType.Town;
                    } else {
                        GlobalData.gameView = EGameType.Home;
                    }
                    // 刷新按钮显示
                    this.updateBtn();
                    LayerGame.instance.initLayer();
                }
                break;

            // 抖音侧边栏领奖
            case 'btnDyReward':
                {
                    // 通过弹窗的方式添加会展示UI层，所以单独处理
                    LoadUtil.instance.loadRes(EBundleType.Game, 'prefab/panel/douyinPropUI', cc.Prefab, (err, res) => {
                        const node = cc.instantiate(res) as cc.Node;
                        node.parent = SceneGame.instance.getToastNode();
                    });
                }
                break;
            // 录屏
            case 'btnRecord':
                {
                    this.recorder(false);
                }
                break;
        }
    }
}